﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace Batalha_Estelar
{
    public class EnemyController
    {
        protected double tempoAux;
        protected const double atrasoNave = 0.2f;

        protected BatalhaEstelar Game { get; set; }
        protected ShipFactory ShipFactory { get; private set; }

        public EnemyController(BatalhaEstelar game)
        {
            this.Game = game;
            this.ShipFactory = new ShipFactory(game);
        }

        public void criarInimigo(GameTime gameTime)
        {
            var config = Game.Config;
            var totalSeconds = gameTime.TotalGameTime.TotalSeconds;
            var enemies = GetEnemies();

            if (totalSeconds > tempoAux && enemies.Count < config.MaxEnemies)
            {
                var r = new Random();
                
                var width = config.FieldWidth;
                var xCenter = (float)(width / 2);
                var displacement = (r.Next() % (int)(width * 0.3)) * GetSignal(r);

                var pIni = new Vector2((float)(xCenter + displacement), 0.0f);

                var newShip = ShipFactory.CreateEnemyShip(pIni);

                tempoAux = gameTime.TotalGameTime.TotalSeconds + atrasoNave;
            }
        }

        public void MoveShips(GameTime gameTime)
        {
            var enemies = GetEnemies();

            if (enemies.Count > 0)
            {
                foreach (var ship in enemies)
                {
                    SetNewDirection(ship);
                    ship.Atirar(gameTime, ship.Posicao);
                }
            }
        }

        #region Helpers

        private List<EnemyShip> GetEnemies()
        {
            return this.Game.State.Query().OfType<EnemyShip>().ToList();
        }

        private void SetNewDirection(Starship ship)
        {
            var dir = new Vector2(0.0f, 1.0f);
            ship.Direcao = dir;
        }

        //Random Direction
        //private void SetNewDirection(Nave ship)
        //{
        //    var r = new Random();

        //    var dx = (float)(r.Next() % 2);
        //    var dy = (float)(r.Next() % 2);

        //    dx *= GetSignal(r);
        //    dy *= GetSignal(r);

        //    var dir = new Vector2(dx, dy);

        //    ship.Direcao = dir;
        //}

        private float GetSignal(Random r)
        {
            return (float)((r.Next() % 2 == 0) ? 1 : -1);
        }

        #endregion
    }
}
